package com.rk.jarjuggler.service;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import com.rk.jarjuggler.model.DirNode;

public class DirFileStore {
    public static void storeTree(DirNode root){
        try {
            FileOutputStream fos = new FileOutputStream("tree.ser");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(root);
            oos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static DirNode loadTree(){
        try {
            InputStream is =  DirFileStore.class.getResourceAsStream("tree.ser");
            if (is == null){
                throw new RuntimeException("Serialized tree not found");
            }
            ObjectInputStream ois = new ObjectInputStream(is);
            DirNode root = (DirNode) ois.readObject();
            ois.close();
            return root;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}
